﻿using UnityEngine;
using System.Collections;
using System;

//////////////////////////////////////////////////////
///颜色工具.
//////////////////////////////////////////////////////

public class ColorUtility {
	const float factor = 1f/255;
	/** 
		hex(0xabcdef)形式转为Unity's Color
	*/
	public static Color Hex(int hex,float alpha){
		float r = ((hex >> 16) & 0xff) * factor;
		float g = ((hex >> 8) & 0xff) * factor;
		float b = (hex & 0xff) * factor;
		return new Color(r,g,b,alpha);
	}
	/** 
		hex(0xaarrggbb) 转为Color
	*/
	public static Color Hex(int hex){
		int rgb = hex & 0x00ffffff;
		float a = ((hex >> 24) & 0xff) * factor;
		
		return Hex(rgb,a);
	}
	/** 0xrrggbb */
	public static Color Hex(string hexString,float alpha){
		try{
			int hex = Convert.ToInt32(hexString.Trim(),16);
			return Hex(hex,alpha);
		}catch(Exception e){
			Debug.Log("颜色值格式不正确:"+hexString+e);
			return Color.black;
		}
	}
	/** 0xaarrggbb */
	public static Color Hex(string hexString){
		string argb = hexString.ToLower();
		int index = argb.IndexOf("0x");
		if (index != -1)
			index += 2;
		string a = argb.Substring(index, 2);
		string rgb = argb.Substring(index + 2);
		float alpha = Convert.ToInt32(a,16) * factor;
		
		return Hex(rgb,alpha);
	}
}
